<?php

/**
* alltosun.com 商品前台控制器 index.php
* ============================================================================
* 版权所有 (C) 2009-2014 北京互动阳光科技有限公司，并保留所有权利。
* 网站地址: http://www.alltosun.com
* ----------------------------------------------------------------------------
* 许可声明: 这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
* ============================================================================
* $Author: 吴松键 (wusj@alltosun.com) $
* $Date: 2014-9-11 下午3:50:37 $
* $Id$
*/

class Action
{
    private $per_page = 12;

    public function __call($action = '', $param = array())
    {
        $goods_id = (int)$action;
        $is_img_details = Request::Get('img_details', 0);
        if (!$goods_id) {
            Response::redirect(AnUrl('goods'));
            Response::flush();
            exit;
        }

        //cheers 活动抢购判断 start
        // $is_cheers = events_helper::get_qualification($goods_id);
        // if($is_cheers !== true) {
        //     if(is_array($is_cheers)) {
        //         return $is_cheers;
        //     }
        // }
        //cheers 活动抢购判断 end

        $goods_info = _uri('goods', array('id'=>$goods_id, 'status'=>1, 'is_sale'=>1));

        if (@$goods_info['flagship'] && @$goods_info['flagship_link']) {
            Response::redirect($goods_info['flagship_link']);
            Response::flush();
            exit;
        }
        if (empty($goods_info)) {
            return array('该商品已经被下架', 'error', AnUrl('goods'));
        }

        $stock = goods_helper::get_stock_by_id($goods_id);

        $sku_id = _uri('sku', array('goods_id'=>$goods_id), 'id');

        $property_ids = _model('sku_relation')->getFields('property_id', array('sku_id'=>$sku_id));

        // 查看快照
        $is_snapshot = 0;
        $order_relation_id = 0;
        $order_relation_id = (int)$param[0];

        if ($order_relation_id > 0) {
            $sku_snapshot_id   = _uri('order_relation', $order_relation_id, 'sku_snapshot_id');

            if ($sku_snapshot_id) {
                $sku_snapshot_info = _uri('sku_snapshot', $sku_snapshot_id);
                $is_snapshot = 1;
                Response::assign('sku_snapshot_info', $sku_snapshot_info);
            }
        }
        $goods_info['cover']   = _uri('attachment', $goods_info['cover'], 'path');
        $goods_info['content'] = htmlspecialchars_decode($goods_info['content']);
        $goods_info['technical'] = htmlspecialchars_decode($goods_info['technical']);

        $property = array();
        foreach ($property_ids as $k=>$v) {
            $property[$v] = count(array_unique(_model('sku_relation')->getFields('property_value_id', array('property_id'=>$v, 'goods_id'=>$goods_id))));
        }
        $sku_list = goods_helper::get_sku_list($goods_id);

        Response::assign('sku_list', $sku_list);
        Response::assign('property', $property);
        Response::assign('goods_id', $goods_id);
        Response::assign('goods_info', $goods_info);
        Response::assign('stock', $stock);
        Response::assign('is_snapshot', $is_snapshot);
        if($is_img_details) {
            if(!is_mobile()){
                Response::redirect(AnUrl("goods/$goods_id"));
            } else {
                Response::display('m/img_details.html');
            }
        } else {
            display_template('detail.html');
        }
    }

    public function sku()
    {
        $id = Request::Get('id', 0);
        if(!$id) {
            return array('访问的页面不存在', 'error', AnUrl('goods'));
        }

        $info = _uri('goods', $id);

        if (!$info) {
            return array('访问的页面不存在', 'error', AnUrl('goods'));
        }

        if ($info['flagship'] == 0 || !$info['flagship_link']) {
            Response::redirect(AnUrl('goods/'.$id));
            return;
        }

        //cheers 活动抢购判断 start
        // $is_cheers = events_helper::get_qualification($id);
        // if($is_cheers !== true) {
        //     if(is_array($is_cheers)) {
        //         return $is_cheers;
        //     }
        // }
        //cheers 活动抢购判断 end

        $stock = goods_helper::get_stock_by_id($id);

        if (!$stock) {
            return array('商品库存不够', 'error', AnUrl());
        }

        $sku_id = _uri('sku', array('goods_id'=>$id), 'id');

        $property_ids = _model('sku_relation')->getFields('property_id', array('sku_id'=>$sku_id));

        $property = array();
        foreach ($property_ids as $k=>$v) {
            $property[$v] = count(array_unique(_model('sku_relation')->getFields('property_value_id', array('property_id'=>$v, 'goods_id'=>$id))));
        }
        $sku_list = goods_helper::get_sku_list($id);

        $list = array();
        $list = _Widget('goods')->get_sku_list(array('goods_id'=>$id));


        if (!is_mobile()) {
            // $sku_id = _uri('sku', array('goods_id'=>$id), 'id');

            // $property_ids = _model('sku_relation')->getFields('property_id', array('sku_id'=>$sku_id));

            // $property = array();
            // foreach ($property_ids as $k=>$v) {
            //     $property[$v] = count(array_unique(_model('sku_relation')->getFields('property_value_id', array('property_id'=>$v, 'goods_id'=>$id))));
            // }
            // $sku_list = goods_helper::get_sku_list($id);

            if (count($sku_list) == 1) {
                if($info['is_direct_buy'] == 1) {
                    // @todo 数量选择
                    Response::redirect(AnUrl("order/trade?sku_id={$sku_list[0]['id']}&num=1"));
                } else {
                    $ret = _widget('cart')->add_cart(array('sku_id'=>$sku_list[0]['id']));
                    if($ret === true) {
                        Response::redirect(AnUrl('cart'));
                    } else {
                        return $ret;
                    }
                }
                return;
            }

            // $list = array();
            // $list = _Widget('goods')->get_sku_list(array('goods_id'=>$id));

            // Response::assign('list', $list);
            // Response::assign('sku_list', $sku_list);
            // Response::assign('property', $property);
        } else {
            $is_promotion = Request::Get('is_promotion', 0);

            // $sku_list = _model('sku')->getList(array('goods_id'=>$id, 'stock >'=>0));
            // 如果只有1个则自动加入购物车
            if (count($sku_list) == 1) {
                if($info['is_direct_buy'] == 1) {
                    // @todo 数量选择
                    Response::redirect(AnUrl("order/trade?sku_id={$sku_list[0]['id']}&num=1"));
                } else {
                    $ret = _widget('cart')->add_cart(array('sku_id'=>$sku_list[0]['id'], 'is_promotion'=>$is_promotion));
                    if($ret === true) {
                        Response::redirect(AnUrl('cart'));
                    } else {
                        return $ret;
                    }
                }
                return;
            }

            $has_img = 0;
            foreach ($sku_list as $k=>$v) {
                // $sku_list[$k]['title'] = $info['title'] . ' ' . goods_helper::get_sku_property($v['id']);
                $cover = _model('attachment_relation')->read(array('res_name'=>'sku', 'res_id'=>$v['id']));
                if ($cover) {
                    $has_img = 1;
                }
            }
            Response::assign('has_img', $has_img);
            // Response::assign('sku_list', $sku_list);
            Response::assign('is_promotion', $is_promotion);
        }

        Response::assign('list', $list);
        Response::assign('sku_list', $sku_list);
        Response::assign('property', $property);

        Response::assign('goods_id', $id);
        Response::assign('goods_info', $info);
        Response::assign('stock', $stock);
        display_template('sku.html');
    }

    public function get_sku_list()
    {
        $id = Request::Get('id', 0);

        if (!$id) {
            return array();
        }

        $list = array();
        $list = goods_helper::get_sku_list($id);

        return array('info'=>'ok', 'sku_list'=>$list);
    }

    public function index()
    {
        $goods_title   = AnFilter::filter_string(Request::Get('goods_title', ''));
        $page          = Request::Get('page_no', 1);
        $status        = Request::Get('status', 1);
        $category      = Request::Get('category', 0);
        $search        = Request::Get('search', 0);
        $stock         = Request::Get('stock', 0);



        $filter = array();
        if (isset($goods_title) && $goods_title) {
            $filter['`title` LIKE '] = '%'.$goods_title.'%';
        }

        if ($stock) {
            $filter['stock >'] = 0;
        }

        if ($category) {
            $filter['category_id'] = $category;
        }

        if ($search == 1) {
            $filter['is_recommend'] =1;
        } else if ($search == 5) {
            $sorting = ' ORDER BY `add_time` DESC ';
        } else if ($search == 10) {
            $sorting = ' ORDER BY `price` DESC ';
        } else if ($search == 15) {
            $sorting = ' ORDER BY `price` ASC ';
        } else {
            $sorting = ' ORDER BY `id` DESC ';
        }

        $filter['is_sale'] = 1;

        $filter['status'] = $status;
        $goods_list = array();
        $goods_count = _model('goods')->getTotal($filter);
        if ($goods_count) {
            $pager = new Pager($this->per_page);
            if ($pager->generate($goods_count)) {
                Response::assign('pager', $pager);
            }
            $goods_list = _model('goods')->getList($filter, $sorting.$pager->getLimit($page));
        }

        Response::assign('goods_count', $goods_count);
        Response::assign('stock', $stock);
        Response::assign('search', $search);
        Response::assign('category', $category);
        Response::assign('goods_title', $goods_title);
        Response::assign('goods_list', $goods_list);
        display_template('goods_list.html');
    }

    public function check_sku()
    {
        $goods_id  = Request::getParam('goods_id', 0);
        $value_ids = Request::getParam('value_ids', '');

        if (!$goods_id) {
            return '当前商品不存在';
        }

        $value_ids = explode(',', $value_ids);
        foreach ($value_ids as $k=>$v) {
            $filter = array(
                    'property_value_id' => $v,
                    'goods_id'          => $goods_id
                );
            $sku_ids[] = _model('sku_relation')->getFields('sku_id', $filter);
        }
        $sku_id_arr = $this->array_intersect_array($sku_ids);

        if (count($sku_id_arr) != 1) {
            return '请选择完整的商品属性值';
        }

        $sku_id = array_pop($sku_id_arr);
        $sku_info = _uri('sku', $sku_id);

        // 获取sku封面
        $file_id = _uri('file_relation', array('res_name'=>'sku', 'res_id'=>$sku_info['id']), 'file_id');
        $cover   = _uri('file', $file_id, 'path');
        $sku_info['cover'] = _image($cover, 'big');

        return array('info'=>'ok', 'sku_info'=>$sku_info);
    }

    /**
     * 求二维数据交集
     */
    private function array_intersect_array($arr)
    {
        $new_arr = array();
        $i = 1;
        foreach ($arr as $k=>$v) {
            if ($i == 1) {
               $new_arr = $v;
            } else {
                $new_arr = array_intersect($new_arr, $v);
            }
            $i++;
        }

        return $new_arr;
    }

    public function select_sku()
    {
        $property_value_id = Request::Post('property_value_id', 0);
        $property_id       = Request::Post('property_id', 0);
        $goods_id          = Request::Post('goods_id', 0);

        if (!$property_id || !$property_value_id || !$goods_id) {
            return '请选择正确的属性';
        }

        $sku_relation_filter = array(
                'property_value_id' => $property_value_id,
                'property_id'       => $property_id,
                'goods_id'          => $goods_id,
        );

        $sku_relation_list = _model('sku_relation')->getList($sku_relation_filter);

        print_r($sku_relation_list);
    }

    public function get_stock()
    {
        $sku_id = Request::Post('sku_id', 0);

        $info = _uri('sku', $sku_id);

        if (!$info) {
            return '该商品不存在';
        }

        // 检查商品
        $goods_info = _uri('goods', $info['goods_id']);

        return array('info'=>'ok', 'stock'=>(int)$info['stock'], 'is_direct_buy'=>(int)$goods_info['is_direct_buy']);
    }

    public function get_sku_cover()
    {
        $id = Request::Post('id', 0);

        if (!$id) {
            return false;
        }

        $cover = _uri('attachment_relation', array('res_id'=>$id, 'res_name'=>'sku'), 'attachment_id');

        if (!$cover) {
            return false;
        }

        $path = _uri('attachment', $cover, 'path');

        if (!$path) {
            return false;
        }

        return array(
                'info'=>'ok',
                'big'=>_image($path, 'big'),
                'list'=>_image($path, 'list')
        );
    }

    /**
     * 仅限测试专用
     * @return [type] [description]
     */
    public function test()
    {
        $arr = array(
                array(1,2,3),
                array('a', 'b', 'c', 'd', 'e'),
                array(4,5,array('L', 'M'),
                array('qq', 'taobao', '163')),
            );

        echo '<pre>';
        print_r($this->product($arr));
    }

    /**
     * 求笛卡尔乘积
     * @param  [type] $arr [数组]
     * @return [type]      [数组]
     */
    private function product($arr)
    {
        if (empty($arr)) {
            return array();
        }

        $tmp_arr = $arr;
        $new_arr = array();
        do{
            $base_arr = $tmp_arr[0];
            unset($tmp_arr[0]);
            if (empty($new_arr)) {
                if (!isset($tmp_arr[1])) {
                    return $base_arr;
                }

                foreach ($tmp_arr[1] as $k => $v) {
                    foreach ($base_arr as $key => $value) {
                        $new_arr[] = array($v, $value);
                    }
                }
                unset($tmp_arr[1]);
            } else {
                $tmp_new_arr = array();
                foreach ($base_arr as $k => $v) {
                    foreach ($new_arr as $key => $value) {
                        $tmp_value = $value;
                        array_push($tmp_value, $v);
                        $tmp_new_arr[] = $tmp_value;
                    }
                }
                $new_arr = $tmp_new_arr;
            }
            $tmp_arr = array_values($tmp_arr);
        } while (isset($tmp_arr[0]) && $tmp_arr[0]);

        return $new_arr;
    }
















}
?>